<?php
/**
 * MerchantController class.
 * MerchantController is for a spesific merchant object.
 * 
 * LBB Solutions Ltd. 版权所有 @ 2012.
 */
class MerchantController extends ApiController
{
	/**
	 * API: merchant/view
	 */
	public function actionView()
	{
		// get id_merchant
		$id_merchant = Yii::app()->request->getParam('id', null);
		if (empty($id_merchant)) $this->_sendError('The parameter "id" is missing!');
		
		$params = array(
			':id_merchant' => $id_merchant,
		);
		
		// get hid (id_user)
		$s_following = null;
		$hid = Yii::app()->request->getParam('hid');
		$key = Yii::app()->request->getParam('key');
		if (!empty($hid) and !empty($key)) {
			$id = $this->_auth($hid, $key);
			$s_following = ', (SELECT f.id_user FROM tbl_user_follow_merchant f
				WHERE f.id_merchant=:id_merchant AND f.id_user=:id_user LIMIT 1) AS following_user_id ';
			$params[':id_user'] = $id;
		}

		// get distance if lat=? and lng=?
		$s_distance = ', NULL AS distance';
		$latitude = Yii::app()->request->getParam('lat');
		$longitude= Yii::app()->request->getParam('lng');
		if (!empty($latitude) and !empty($longitude)) {
			$s_distance = ', (6371 * acos(cos(radians(:lat)) * cos(radians(m.latitude)) * cos(radians(m.longitude) - radians(:lng)) + sin(radians(:lat)) * sin(radians(m.latitude)))) AS distance';
			$params[':lat'] = (double)$latitude;
			$params[':lng'] = (double)$longitude;
		}
		
		$sql_merchant = 'SELECT m.id, m.name, m.biz_area, m.address, m.postcode, m.phone, m.city, m.country_code, m.currency_code,
			m.url_logo, m.url_site, m.latitude, m.longitude, m.opening, m.brief, m.average_price,
			m.category_key, m.enable_rewards,
			t.cuisine_style, t.cuisine_type, t.meal_served, t.payment_options, t.service_languages, 
			t.alcohol_license, t.dining_ambience, t.car_parking, t.additional_details
			' . $s_distance . $s_following . '
			FROM tbl_merchant_account m
			LEFT JOIN tbl_merchant_tags t ON m.id=t.id_merchant
			WHERE m.id=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchant);
		$row = $command->queryRow(true, $params);
		
		//2. fetch special
		$sql_special = 'SELECT COUNT(id) as specials
			FROM tbl_merchant_special
			WHERE id_merchant=:id_merchant
			AND trash=0 AND status=1 AND start_date<NOW() AND end_date>NOW()';
		$command = $connection->createCommand($sql_special);
		$row['specials'] = $command->queryAll(true, array(':id_merchant'=>$id_merchant));
		
		//3. get meals : max = 6
		$sql_dishes = 'SELECT i.id, i.id_merchant, i.url_picture, i.name, i.price, i.price_flexible, i.featured, i.sensitive_code
			FROM tbl_merchant_menu_item i
			WHERE i.id_merchant=:id_merchant
			ORDER BY i.featured DESC, i.submitted_time DESC
			LIMIT 6';
		$command = $connection->createCommand($sql_dishes);
		$row['meals'] = $command->queryAll(true, array(':id_merchant'=>$id_merchant));
		
		//4. get merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$row['hours'] = $command->queryAll(true, array(':id_merchant'=>$id_merchant));
		
		//5. get gallery: max=9
		$sql_gallery = 'SELECT id, url_picture FROM tbl_merchant_gallery
			WHERE id_merchant=:id_merchant ORDER BY create_time DESC LIMIT 9';
		$command = $connection->createCommand($sql_gallery);
		$row['gallery'] = $command->queryAll(true, array(':id_merchant'=>$id_merchant));
		
		$connection->active = false;
		
		$this->_sendJSON(200, $this->_mkMerchant($row));
	}
	
	/**
	 * API: merchant/detail
	 */
	public function actionDetail()
	{
		// get id_merchant
		$id_merchant = Yii::app()->request->getParam('id', null);
		if (empty($id_merchant)) $this->_sendError('The parameter "id" is missing!');
		
		$params = array(
			':id_merchant' => $id_merchant,
		);
		
		$sql_merchant = 'SELECT m.id, m.name, m.biz_area, m.url_site, m.currency_code, m.brief, m.category_key,
			t.cuisine_style, t.cuisine_type, t.meal_served, t.payment_options, t.service_languages, 
			t.alcohol_license, t.dining_ambience, t.car_parking, t.additional_details
			FROM tbl_merchant_account m
			LEFT JOIN tbl_merchant_tags t ON m.id=t.id_merchant
			WHERE m.id=:id_merchant';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchant);
		$row = $command->queryRow(true, $params);
		
		//2. fetch special
		$sql_special = 'SELECT COUNT(id) as specials
			FROM tbl_merchant_special
			WHERE id_merchant=:id_merchant
			AND trash=0 AND status=1 AND start_date<NOW() AND end_date>NOW()';
		$command = $connection->createCommand($sql_special);
		$row['specials'] = $command->queryAll(true, $params);
		
		//3. get meals : max = 6
		$sql_dishes = 'SELECT i.id, i.id_merchant, i.url_picture, i.name, i.price, i.price_flexible, i.featured, i.sensitive_code
			FROM tbl_merchant_menu_item i
			WHERE i.id_merchant=:id_merchant
			ORDER BY i.featured DESC, i.submitted_time DESC
			LIMIT 6';
		$command = $connection->createCommand($sql_dishes);
		$row['meals'] = $command->queryAll(true, array(':id_merchant'=>$id_merchant));
		
		//4. get merchant's open hours
		$sql_hours = 'SELECT week_no, open_hour, close_hour FROM tbl_merchant_open_hours
			WHERE id_merchant=:id_merchant ORDER BY week_no ASC';
		$command = $connection->createCommand($sql_hours);
		$row['hours'] = $command->queryAll(true, array(':id_merchant'=>$id_merchant));
		
		//5. get gallery: max=3
		$sql_gallery = 'SELECT id, url_picture FROM tbl_merchant_gallery
			WHERE id_merchant=:id_merchant ORDER BY create_time DESC LIMIT 3';
		$command = $connection->createCommand($sql_gallery);
		$row['gallery'] = $command->queryAll(true, array(':id_merchant'=>$id_merchant));
		
		$connection->active = false;
		
		$this->_sendJSON(200, $this->_mkMerchantDetail($row));
	}
	
	/**
	 * API: merchant/follow
	 * follow/unfollow a merchant
	 */
	public function actionFollow()
	{
		// get hid
		$hid = Yii::app()->request->getParam('hid', null);
		$key = Yii::app()->request->getParam('key', null);
		if (empty($hid) or empty($key)) {
			$this->_sendJSON(300, BUtils::T('no_login_follow_merchant_msg'));
		}
		$id = $this->_auth($hid, $key);
		
		// get id_merchant
		$id_merchant = Yii::app()->request->getParam('id', null);
		if (empty($id_merchant)) $this->_sendError('The parameter "id" is missing!');
		
		// get follow=true/false
		$follow = Yii::app()->request->getParam('follow', 0);
		
		$params = array(
			':id_user' => $id,
			':id_merchant' => $id_merchant,
		);
		$sql_delete = 'DELETE FROM tbl_user_follow_merchant WHERE id_user=:id_user AND id_merchant=:id_merchant';
		$sql_insert = 'INSERT INTO tbl_user_follow_merchant (id_user, id_merchant) VALUES (:id_user, :id_merchant)';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_delete);
		$command->execute($params);
		if ($follow == 1) {
			$command = $connection->createCommand($sql_insert);
			$command->execute($params);
		}
		$connection->active = false;
		
		$this->_sendJSON(200, array(
			'id' => $id_merchant,
			'following' => ($follow == 1) ? 1 : 0,
		));
	}
	
	/**
	 * Make merchants list
	 * @param array $rows
	 * @return array
	 */
	protected function _mkMerchant($r) {
		$categoriesIndex = BUtils::CategoriesNo();
		
		//following
		if (empty($r['following_user_id'])) {
			$following = 0;
		} else {
			$following = 1;
		}

		//logo
		$url_logo = 'http://yamii.fi/img/default_special_thumb.png';
		if (!empty($r['url_logo'])) {
			$url_logo = 'http://yamii.fi/business' . $r['url_logo'];
		}
		
		//hours
		$hours = array();
		if (!empty($r['hours'])) {
			//define array
			$aWeekDaysShort = BUtils::WeekDayKeys(7, true);
			$aOpenningHours = BUtils::AllHour24();
			
			//set open hours display style
			$sWeekBuffer = array();
			foreach ($r['hours'] as $v) {
				$sWeekday = $aWeekDaysShort[$v['week_no']];
				$sHours = $aOpenningHours[$v['open_hour']] . ' - ' . $aOpenningHours[$v['close_hour']];
				$sWeekBuffer[$sHours][] = $v['week_no'];//add the current week day
			}
			$i = 0;
			foreach ($sWeekBuffer as $key => $v) {
				$size = count($v);
				if ($size > 1) $sWeekday = $aWeekDaysShort[$v[0]] . '-' . $aWeekDaysShort[$v[$size-1]];
				else $sWeekday = $aWeekDaysShort[$v[0]];
				$hours[] = $sWeekday . ': '. $key;
			}
		}
		
		//meals
		$meals = array();
		foreach ($r['meals'] as $v) {
			$meals[] = array(
				'name' => $v['name'],
				'price' => $v['price'],
			);
		}
		
		//gallery
		$gallery = array();
		foreach ($r['gallery'] as $v) {
			$gallery[] = array(
				'url' => 'http://yamii.fi/business' . str_replace('thumb_', '', $v['url_picture']),
				'url_thumb' => 'http://yamii.fi/business' . $v['url_picture'],
			);
		}
		
		// $category
		$category = BUtils::T($r['category_key']);
		$cate_no = (int)$categoriesIndex[$r['category_key']];
		
		//url_detailview
		$url_detailview = Yii::app()->createAbsoluteUrl('/mobile/merchant/detail', array(
			'id' => $r['id'],
			'lang' => Yii::app()->language));
		
		//enable rewards: To commented out to enable it
		$r['enable_rewards'] = 0;
		return array(
			'id' => $r['id'],
			'name' => $r['name'],
			'category' => $category,
			'category_no' => $cate_no,
			'url_logo' => $url_logo,
			'area' => empty($r['biz_area']) ? '' : $r['biz_area'],
			'address' => empty($r['address']) ? '' : $r['address'],
			'zip' => $r['postcode'],
			'city' => $r['city'],
			'phone' => MerchantObject::formatPhoneNumber($r['phone']),
			'distance' => empty($r['distance']) ? null : (float)$r['distance'],
			'lat' => (float)$r['latitude'],
			'lng' => (float)$r['longitude'],
			'brief' => $r['brief'],
			'tags' => array(),
			'following' => $following,
			'offers' => (int)$r['specials'],//current offers
			'enable_rewards' => (int)$r['enable_rewards'],//enable for 1
			'average_price' => '',
			'url_detailview' => $url_detailview,
			'url_website' => $r['url_site'],
			'open_hours' => $hours,
			'meals' => $meals,
			'gallery' => $gallery,
			//TODO: the following new features
			//add the merchants in same group
			//add the merchants nearby
		);
	}
	
	/**
	 * Make merchant detail info
	 * @param array $rows
	 * @return array
	 */
	protected function _mkMerchantDetail($r) {
		//tags
		//t.cuisine_style, t.cuisine_type, t.meal_served, t.payment_options, t.service_languages, t.alcohol_license, t.dining_ambience, t.car_parking, t.additional_details
		$tags = array();
		$keys = array('cuisine_style', 'cuisine_type', 'meal_served', 'payment_options', 'service_languages', 'alcohol_license', 'dining_ambience', 'car_parking', 'additional_details');
		$i = 0;
		foreach ($keys as $key) {
			if (!empty($r[$key])) {
				if ($i === 0) { $tags[] = array($key, BUtils::T($key . '_lbl') . ':'); }
				else { $tags[] = array($key, "\n" . BUtils::T($key . '_lbl') . ':'); }
				foreach (explode(',', $r[$key]) as $t) {
					$tags[] = array($t, BUtils::T($t));
				}
				$i ++;
			}
		}

		//hours
		$hours = array();
		if (!empty($r['hours'])) {
			//define array
			$aWeekDaysShort = BUtils::WeekDayKeys(7, true);
			$aOpenningHours = BUtils::AllHour24();
			
			//set open hours display style
			$sWeekBuffer = array();
			foreach ($r['hours'] as $v) {
				$sWeekday = $aWeekDaysShort[$v['week_no']];
				$sHours = $aOpenningHours[$v['open_hour']] . ' - ' . $aOpenningHours[$v['close_hour']];
				$sWeekBuffer[$sHours][] = $v['week_no'];//add the current week day
			}
			$i = 0;
			foreach ($sWeekBuffer as $key => $v) {
				$size = count($v);
				if ($size > 1) $sWeekday = $aWeekDaysShort[$v[0]] . '-' . $aWeekDaysShort[$v[$size-1]];
				else $sWeekday = $aWeekDaysShort[$v[0]];
				$hours[] = $sWeekday . ': '. $key;
			}
		}
		
		//meals
		$meals = array();
		foreach ($r['meals'] as $v) {
			$meals[] = array(
				'name' => $v['name'],
				'price' => $v['price'],
			);
		}
		
		return array(
			'id' => $r['id'],
			'name' => $r['name'],
			'brief' => $r['brief'],
			'tags' => $tags,
			'open_hours' => $hours,
			'meals' => $meals,
		);
	}
}